<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.6"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Arduino A2DP: A Simple Arduino Bluetooth Music Receiver and Sender for the ESP32</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr id="projectrow">
  <td id="projectalign">
   <div id="projectname">Arduino A2DP
   </div>
  </td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.9.6 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&amp;dn=expat.txt MIT */
var searchBox = new SearchBox("searchBox", "search/",'.html');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&amp;dn=expat.txt MIT */
$(function() {
  initMenu('',true,false,'search.php','Search');
  $(document).ready(function() { init_search(); });
});
/* @license-end */
</script>
<div id="main-nav"></div>
</div><!-- top -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<div id="MSearchResults">
<div class="SRPage">
<div id="SRIndex">
<div id="SRResults"></div>
<div class="SRStatus" id="Loading">Loading...</div>
<div class="SRStatus" id="Searching">Searching...</div>
<div class="SRStatus" id="NoMatches">No Matches</div>
</div>
</div>
</div>
</div>

<div><div class="header">
  <div class="headertitle"><div class="title">A Simple Arduino Bluetooth Music Receiver and Sender for the ESP32 </div></div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p><a class="anchor" id="md_README"></a> The ESP32 is a microcontroller that provides an API for Bluetooth A2DP which can be used to receive sound data e.g. from your Mobile Phone and makes it available via a callback method. The output is a PCM data stream, decoded from SBC format. The documentation can be found <a href="https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/i2s.html">here</a>.</p>
<p><img src="https://pschatzmann.github.io/ESP32-A2DP/img/esp32.jpeg" alt="esp32" class="inline"/></p>
<p>I2S is an electrical serial bus interface standard used for connecting digital audio devices together. It is used to communicate PCM audio data between integrated circuits in an electronic device.</p>
<p>So we can just feed the input from Bluetooth to the I2S output: An example for this from Espressif can be found on <a href="https://github.com/espressif/esp-idf/tree/master/examples/bluetooth/bluedroid/classic_bt/a2dp_sink">Github</a>.</p>
<p>Unfortunately this example did not make me happy so I decided to convert it into a simple <b>Arduino Library</b> that is very easy to use from an Arduino Software IDE.</p>
<h1><a class="anchor" id="autotoc_md1"></a>
Supported Bluetooth Protocols</h1>
<p>As the name of this libariy implies, it supports the A2DP <a href="https://en.wikipedia.org/wiki/List_of_Bluetooth_profiles">Bluetooth protocol</a> which only provides audio streaming!</p>
<p>It also supports Audio/Video Remote Control Profile (AVRCP) together with A2DP.</p>
<p>The Hands-Free Profile (HFP), Headset Profile (HSP) and stand alone AVRCP without A2DP are <b>not</b> supported!</p>
<h1><a class="anchor" id="autotoc_md2"></a>
A2DP Sink (Music Receiver)</h1>
<p>This can be used e.g. to build your own Bluetooth Speaker.</p>
<h2><a class="anchor" id="autotoc_md3"></a>
A Simple I2S Example (A2DS Sink) using default Pins</h2>
<p>Here is the simplest example which just uses the proper default settings:</p>
<div class="fragment"><div class="line">#include &quot;BluetoothA2DPSink.h&quot;</div>
<div class="line"> </div>
<div class="line">BluetoothA2DPSink a2dp_sink;</div>
<div class="line"> </div>
<div class="line">void setup() {</div>
<div class="line">    a2dp_sink.start(&quot;MyMusic&quot;);</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">void loop() {</div>
<div class="line">}</div>
</div><!-- fragment --><p> This creates a new Bluetooth device with the name “MyMusic” and the output will be sent to the following default I2S pins which need to be conected to an external DAC:</p><ul>
<li>bck_io_num = 26</li>
<li>ws_io_num = 25</li>
<li>data_out_num = 22</li>
</ul>
<h2><a class="anchor" id="autotoc_md4"></a>
Defining Pins</h2>
<p>You can define your own pins easily by calling the <code>set_pin_config</code> method in the setup before the <code>start</code>.</p>
<div class="fragment"><div class="line">#include &quot;BluetoothA2DPSink.h&quot;</div>
<div class="line"> </div>
<div class="line">BluetoothA2DPSink a2dp_sink;</div>
<div class="line"> </div>
<div class="line">void setup() {</div>
<div class="line">    i2s_pin_config_t my_pin_config = {</div>
<div class="line">        .bck_io_num = 26,</div>
<div class="line">        .ws_io_num = 25,</div>
<div class="line">        .data_out_num = 22,</div>
<div class="line">        .data_in_num = I2S_PIN_NO_CHANGE</div>
<div class="line">    };</div>
<div class="line">    a2dp_sink.set_pin_config(my_pin_config);</div>
<div class="line">    a2dp_sink.start(&quot;MyMusic&quot;);</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">void loop() {</div>
<div class="line">}</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md5"></a>
Using your specific i2s_config</h2>
<p>In some cases you might want to use your specific i2s_config settings. E.g. to request a different bits_per_sample (e.g. 32) or to use the use_apll or to optimize the dma buffer...</p>
<div class="fragment"><div class="line">#include &quot;BluetoothA2DPSink.h&quot;</div>
<div class="line"> </div>
<div class="line">BluetoothA2DPSink a2dp_sink;</div>
<div class="line"> </div>
<div class="line">void setup() {</div>
<div class="line"> </div>
<div class="line">    static i2s_config_t i2s_config = {</div>
<div class="line">      .mode = (i2s_mode_t) (I2S_MODE_MASTER | I2S_MODE_TX),</div>
<div class="line">      .sample_rate = 44100, // updated automatically by A2DP</div>
<div class="line">      .bits_per_sample = (i2s_bits_per_sample_t)32,</div>
<div class="line">      .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,</div>
<div class="line">      .communication_format = (i2s_comm_format_t) (I2S_COMM_FORMAT_STAND_I2S),</div>
<div class="line">      .intr_alloc_flags = 0, // default interrupt priority</div>
<div class="line">      .dma_buf_count = 8,</div>
<div class="line">      .dma_buf_len = 64,</div>
<div class="line">      .use_apll = true,</div>
<div class="line">      .tx_desc_auto_clear = true // avoiding noise in case of data unavailability</div>
<div class="line">  };</div>
<div class="line">  a2dp_sink.set_i2s_config(i2s_config);</div>
<div class="line">  a2dp_sink.start(&quot;MyMusic&quot;);</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">void loop() {</div>
<div class="line">}</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md6"></a>
Output to the Internal DAC</h2>
<p>You can also send the output directly to the internal DAC of the ESP32 by providing the corresponding i2s_config:</p>
<div class="fragment"><div class="line">#include &quot;BluetoothA2DPSink.h&quot;</div>
<div class="line"> </div>
<div class="line">BluetoothA2DPSink a2dp_sink;</div>
<div class="line"> </div>
<div class="line">void setup() {</div>
<div class="line">    static const i2s_config_t i2s_config = {</div>
<div class="line">        .mode = (i2s_mode_t) (I2S_MODE_MASTER | I2S_MODE_TX | I2S_MODE_DAC_BUILT_IN),</div>
<div class="line">        .sample_rate = 44100, // corrected by info from bluetooth</div>
<div class="line">        .bits_per_sample = (i2s_bits_per_sample_t) 16, /* the DAC module will only take the 8bits from MSB */</div>
<div class="line">        .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,</div>
<div class="line">        .communication_format = (i2s_comm_format_t)I2S_COMM_FORMAT_STAND_MSB,</div>
<div class="line">        .intr_alloc_flags = 0, // default interrupt priority</div>
<div class="line">        .dma_buf_count = 8,</div>
<div class="line">        .dma_buf_len = 64,</div>
<div class="line">        .use_apll = false</div>
<div class="line">    };</div>
<div class="line"> </div>
<div class="line">    a2dp_sink.set_i2s_config(i2s_config);</div>
<div class="line">    a2dp_sink.start(&quot;MyMusic&quot;);</div>
<div class="line"> </div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">void loop() {</div>
<div class="line">}</div>
</div><!-- fragment --><p>The output goes now to the DAC pins GPIO25 (Channel 1) and GPIO26 (Channel 2).</p>
<h2><a class="anchor" id="autotoc_md7"></a>
Accessing the Sink Data Stream with Callbacks</h2>
<p>You can be notified when a packet is received. The API is using PCM data normally formatted as 44.1kHz sampling rate, two-channel 16-bit sample data.</p>
<div class="fragment"><div class="line">// In the setup function:</div>
<div class="line">a2dp_sink.set_on_data_received(data_received_callback);</div>
<div class="line"> </div>
<div class="line"> </div>
<div class="line">// Then somewhere in your sketch:</div>
<div class="line">void data_received_callback() {</div>
<div class="line">  Serial.println(&quot;Data packet received&quot;);</div>
<div class="line">}</div>
</div><!-- fragment --><p>Or you can access the packet:</p>
<div class="fragment"><div class="line">// In the setup function:</div>
<div class="line">a2dp_sink.set_stream_reader(read_data_stream);</div>
<div class="line"> </div>
<div class="line">// Then somewhere in your sketch:</div>
<div class="line">void read_data_stream(const uint8_t *data, uint32_t length)</div>
<div class="line">{</div>
<div class="line">  int16_t *samples = (int16_t*) data;</div>
<div class="line">  uint32_t sample_count = length/2;</div>
<div class="line">  // Do something with the data packet</div>
<div class="line">}</div>
</div><!-- fragment --><p> In the <code>a2dp_sink.set_stream_reader()</code> method you can provide an optional parameter that defines if you want the output to I2S to be active or deactive - So you can use this method to e.g. to switch off I2S just by calling <code>a2dp_sink.set_stream_reader(read_data_stream, false)</code></p>
<h2><a class="anchor" id="autotoc_md8"></a>
Support for Metadata</h2>
<p>You can register a method which will be called when the system receives any AVRC metadata. Here is an example </p><div class="fragment"><div class="line">void avrc_metadata_callback(uint8_t data1, const uint8_t *data2) {</div>
<div class="line">  Serial.printf(&quot;AVRC metadata rsp: attribute id 0x%x, %s\n&quot;, data1, data2);</div>
<div class="line">}</div>
<div class="line">a2dp_sink.set_avrc_metadata_callback(avrc_metadata_callback);</div>
<div class="line">a2dp_sink.start(&quot;BT&quot;);</div>
</div><!-- fragment --><p> By default you should get the most important information, however you can adjust this by calling the <code>set_avrc_metadata_attribute_mask</code> method e.g if you just need the title and playing time you can call: </p><div class="fragment"><div class="line">set_avrc_metadata_attribute_mask(ESP_AVRC_MD_ATTR_TITLE | ESP_AVRC_MD_ATTR_PLAYING_TIME);</div>
</div><!-- fragment --><p> before you start the A2DP sink.</p>
<h2><a class="anchor" id="autotoc_md9"></a>
Support for AVRC Commands</h2>
<p>I have added the following AVRC commmands, that you can use to 'control' your A2DP Source:</p>
<ul>
<li>play();</li>
<li>pause();</li>
<li>stop();</li>
<li>next();</li>
<li>previous();</li>
<li>fast_forward();</li>
<li>rewind();</li>
</ul>
<h1><a class="anchor" id="autotoc_md10"></a>
A2DP Source (Music Sender)</h1>
<p>This can be used to feed e.g. your Bluetooth Speaker with your audio data.</p>
<h2><a class="anchor" id="autotoc_md11"></a>
Sending Data from a A2DS Data Source with a Callback</h2>
<p>We can also generate sound and send it e.g. to a Bluetooth Speaker. <br  />
</p>
<p>The supported audio codec in ESP32 A2DP is SBC: The API is using PCM data normally formatted as 44.1kHz sampling rate, two-channel 16-bit sample data.</p>
<p>When you start the <a class="el" href="class_bluetooth_a2_d_p_source.html" title="A2DP Bluetooth Source.">BluetoothA2DPSource</a>, you need to pass the Bluetooth name that you want to connect to and a 'call back function' that generates the sound data:</p>
<div class="fragment"><div class="line">#include &quot;BluetoothA2DPSource.h&quot;</div>
<div class="line"> </div>
<div class="line">BluetoothA2DPSource a2dp_source;</div>
<div class="line"> </div>
<div class="line">// callback </div>
<div class="line">int32_t get_sound_data(Frame *data, int32_t frameCount) {</div>
<div class="line">    // generate your sound data </div>
<div class="line">    // return the effective length (in frames) of the generated sound  (which usually is identical with the requested len)</div>
<div class="line">    // 1 frame is 2 channels * 2 bytes = 4 bytes</div>
<div class="line">    return frameCount;</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">void setup() {</div>
<div class="line">  a2dp_source.start(&quot;MyMusic&quot;, get_sound_data);  </div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">void loop() {</div>
<div class="line">}</div>
</div><!-- fragment --><p>In the examples you can find an implentation that generates sound with the help of the sin() function. You can also inticate multiple alternative Bluetooth names. The system just connects to the first one which is available:</p>
<div class="fragment"><div class="line">void setup() {</div>
<div class="line">  static std::vector&lt;char*&gt; bt_names = {&quot;MyMusic&quot;,&quot;RadioPlayer&quot;,&quot;MusicPlayer&quot;};</div>
<div class="line">  a2dp_source.start(bt_names, get_sound_data); </div>
<div class="line">} </div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md12"></a>
Sending Data from a A2DS Data Source with Recorded Data</h2>
<p>You can also provide the data directly as simple array of uint8_t:</p>
<div class="fragment"><div class="line">#include &quot;BluetoothA2DPSource.h&quot;</div>
<div class="line"> </div>
<div class="line">extern const uint8_t StarWars10_raw[];</div>
<div class="line">extern const unsigned int StarWars10_raw_len;</div>
<div class="line"> </div>
<div class="line">BluetoothA2DPSource a2dp_source;</div>
<div class="line">SoundData *music = new OneChannelSoundData((int16_t*)StarWars30_raw, StarWars30_raw_len/2);</div>
<div class="line"> </div>
<div class="line">void setup() {</div>
<div class="line">  a2dp_source.start(&quot;RadioPlayer&quot;);  </div>
<div class="line">  a2dp_source.write_data(music);</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">void loop() {</div>
<div class="line">}</div>
</div><!-- fragment --><p>The array can be prepared e.g. in the following way:</p>
<ul>
<li>Open any sound file in Audacity.<ul>
<li>Select Tracks -&gt; Resample and select 44100</li>
<li>Export -&gt; Export Audio -&gt; Header Raw ; Signed 16 bit PCM</li>
</ul>
</li>
<li>Convert to c file e.g. with "xxd -i file_example_WAV_1MG.raw file_example_WAV_1MG.c"<ul>
<li>add the const qualifier to the generated array definition. E.g const unsigned char file_example_WAV_1MG_raw[] = {</li>
</ul>
</li>
</ul>
<p>You might want to compile with the Partition Scheme: Huge App!</p>
<p>In the example above we provide the data with one channel. This has the advantage that it uses much less space then a 2 channel recording, which you could use in the following way:</p>
<div class="fragment"><div class="line">SoundData *data = new TwoChannelSoundData((Frame*)StarWars10_raw,StarWars10_raw_len/4);</div>
</div><!-- fragment --><p>In the constructor you can pass additional parameters:</p>
<div class="fragment"><div class="line">TwoChannelSoundData(Frame *data, int32_t frameCount, bool loop=false);</div>
<div class="line">OneChannelSoundData(int16_t *data, int32_t frameCount, bool loop=false, ChannelInfo channelInfo=Both);</div>
<div class="line">OneChannel8BitSoundData(int8_t *data, int32_t frameCount, bool loop=false, ChannelInfo channelInfo=Both);</div>
</div><!-- fragment --> <h1><a class="anchor" id="autotoc_md13"></a>
Logging</h1>
<p>This library uses the ESP32 logger that you can activate in Arduino in - Tools - Core Debug Log.</p>
<h1><a class="anchor" id="autotoc_md14"></a>
Architecture / Dependencies</h1>
<p>The current code is purely dependent on the ESP-IDF (which is also provided by the Arduino ESP32 core). There are no other dependencies and this includes the Arduino API!</p>
<p>Therefore we support:</p>
<ul>
<li>Arduino</li>
<li><a href="https://github.com/pschatzmann/ESP32-A2DP/wiki/PlatformIO">PlatformIO</a></li>
<li><a href="https://github.com/pschatzmann/ESP32-A2DP/wiki/Espressif-IDF-as-a-Component">Espressif IDF</a></li>
</ul>
<p>This restriction limits however the provided examples.</p>
<p>Before you clone the project, please read the following information which can be found in the <a href="https://github.com/pschatzmann/ESP32-A2DP/wiki/Design-Overview">Wiki</a>.</p>
<h1><a class="anchor" id="autotoc_md15"></a>
Digital Sound Processing</h1>
<p>You can use this library stand alone, but it is part of my <a href="https://github.com/pschatzmann/arduino-audio-tools">audio-tools</a> project. So you can easily enhance this functionality with sound effects, use filters, use alternative audio sinks or audio sources, do FFT etc. Here is a <a href="https://github.com/pschatzmann/arduino-audio-tools/blob/main/examples/examples-basic-api/basic-a2dp-fft/basic-a2dp-fft.ino">simple example</a> how you can analyse the audio data with FFT.</p>
<h1><a class="anchor" id="autotoc_md16"></a>
Documentation</h1>
<ul>
<li>The <a href="https://pschatzmann.github.io/ESP32-A2DP/html/group__a2dp.html">class documentation can be found here</a></li>
<li>You can also find further information in the <a href="https://github.com/pschatzmann/ESP32-A2DP/wiki">Wiki</a></li>
</ul>
<h1><a class="anchor" id="autotoc_md17"></a>
Support</h1>
<p>I spent a lot of time to provide a comprehensive and complete documentation. So please read the documentation first and check the issues and discussions before posting any new ones on Github.</p>
<p>Open issues only for bugs and if it is not a bug, use a discussion: Provide enough information about</p><ul>
<li>the selected scenario/sketch</li>
<li>what exactly you are trying to do</li>
<li>your hardware</li>
<li>your software versions</li>
</ul>
<p>to enable others to understand and reproduce your issue.</p>
<p>Finally above all <b>don't</b> send me any e-mails or post questions on my personal website!</p>
<h1><a class="anchor" id="autotoc_md18"></a>
Show and Tell</h1>
<p>Get some inspiration <a href="https://github.com/pschatzmann/ESP32-A2DP/discussions/categories/show-and-tell">from projects that were using this library</a> and share your projects with the community.</p>
<h1><a class="anchor" id="autotoc_md19"></a>
Installation</h1>
<p>For Arduino you can download the library as zip and call include Library -&gt; zip library. Or you can git clone this project into the Arduino libraries folder e.g. with </p><div class="fragment"><div class="line">cd  ~/Documents/Arduino/libraries</div>
<div class="line">git clone https://github.com/pschatzmann/ESP32-A2DP.git</div>
</div><!-- fragment --><p>For other frameworks <a href="https://github.com/pschatzmann/ESP32-A2DP/wiki">see the Wiki</a></p>
<h1><a class="anchor" id="autotoc_md20"></a>
Change History</h1>
<p>The <a href="https://github.com/pschatzmann/ESP32-A2DP/wiki/Change-History">Change History can be found in the Wiki</a></p>
<h1><a class="anchor" id="autotoc_md21"></a>
Sponsor Me</h1>
<p>This software is totally free, but you can make me happy by rewarding me with a treat</p>
<ul>
<li><a href="https://www.buymeacoffee.com/philschatzh">Buy me a coffee</a></li>
<li><a href="https://paypal.me/pschatzmann?country.x=CH&amp;locale.x=en_US">Paypal me</a> </li>
</ul>
</div></div><!-- PageDoc -->
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by&#160;<a href="https://www.doxygen.org/index.html"><img class="footer" src="doxygen.svg" width="104" height="31" alt="doxygen"/></a> 1.9.6
</small></address>
</body>
</html>
